/*
 * @Description: 电子文件挂接弹窗
 * @Author: Rfan
 * @Date: 2022-02-28 14:38:33
 * @LastEditTime: 2023-01-10 21:38:00
 */

import { useEffect, useState } from 'react';
import { Button, message, Modal, Space, Table, Upload } from 'antd';
import classNames from 'classnames/bind';
import { useFormatMessage } from '@/utils/intlHelpers';
import { delItemById, delItemByIdArray } from '@/utils/list';
import { IUploadResourceResponse, uploadResource } from '@/api/upload';
import { addERecords, deleteERecords, IDeleteArchiveParams } from '@/api/archives/archives';
import type { ICommonDialog } from '@/interfaces/global';
import styles from '../../styles/linkDialog.module.scss';
import { byteConvert, jsonClone } from '@/utils';
import { useReceiveAndSendCollectionContext } from '../../contexts/ReceiveAndSendCollectionContext';

const cx = classNames.bind(styles);
const { Column } = Table;

interface ILinkDialogProps extends ICommonDialog {
  query: any;
  info: any;
}

const LinkDialog = (props: ILinkDialogProps) => {
  const { visible, query, info, onClose } = props;
  const { addTableItem, delTableItem } = useReceiveAndSendCollectionContext();
  const formatMessage = useFormatMessage();
  // 选中文件列表
  const [uploadList, setUploadList] = useState([]);
  // 选中文件列表
  const [uploadTableLoading, setUploadTableLoading] = useState(false);
  // 挂接文件列表
  const [linkedList, setLinkedList] = useState([]);

  useEffect(() => {
    console.log('info ', { query, info });
    setUploadList([]);
    setLinkedList([]);
  }, [visible]);

  const handleOk = () => {};

  const handelCancel = () => {
    clearUploadList();
    onClose();
  };

  /**
   * @description: upload组件上传前钩子，处理选中的文件列表
   * @param {File} file
   */
  const beforeUpload = (file: File) => {
    console.log('filefifi', file);

    setUploadList((state) => [...state, file]);
    console.log('uploadList', uploadList);

    // return false;
  };

  /**
   * @description: 从【已选择文件】列表中删除条目
   * @param {string} key
   */
  const delUploadItem = (key: string): void => {
    setUploadList(delItemById(key, uploadList, 'uid'));
  };

  /**
   * @description: 从【已选择文件】列表中删除条目
   */
  const clearUploadList = (): void => {
    setUploadList([]);
  };

  /**
   * @description: 上传选中的文件
   * @param {File[]} fileList
   * @param {'batch' | 'single'} type 上传类型，批量上传还是单个文件上传
   */
  const uploadFileFunc = (fileList: File[], type?: 'batch' | 'single'): void => {
    if (type === 'batch') {
      setUploadTableLoading(true);
    }
    const formData = new FormData();
    fileList.forEach((file: File) => {
      formData.append('files', file);
    });

    uploadResource(formData)
      .then((res: any) => {
        const fileList: IUploadResourceResponse[] = res.data;
        const { commonParams, atCode, atType, level } = query;
        const params = {
          commonParams,
          file_id: info.id,
          coordinate: {
            atCode,
            atType,
            level
          },
          originalFileBeanList: fileList.map((item, idx) => ({
            file_ext: item.ext,
            file_name: item.name,
            file_path: item.path,
            file_size: item.size,
            file_url: item.url,
            sort_no: idx + 1
          }))
        };
        addERecords(params)
          .then((res: any) => {
            const data = res.data || [];
            addTableItem(data[0]);
            setLinkedList((state: any) => [...state, ...data]);
            clearUploadList();
          })
          .finally(() => {
            setUploadTableLoading(false);
          });
      })
      .finally(() => {
        setUploadTableLoading(false);
      });
  };

  /**
   * @description: 删除选中条目
   * @param {number} id
   */
  const delSelectFile = (id: number) => {
    const formatQuery = jsonClone(query);
    delete formatQuery.levelNum;
    delete formatQuery.downLevelId;

    const params: IDeleteArchiveParams = {
      ...formatQuery,
      entryIdList: [id]
    };
    deleteERecords(params).then((res) => {
      delTableItem(res.data);
      message.success('删除成功');
      setLinkedList((state) => delItemByIdArray(res.data, state));
    });
  };

  return (
    <Modal
      title="挂接电子文件"
      visible={visible}
      width={800}
      footer={null}
      onOk={handleOk}
      onCancel={handelCancel}
    >
      <div className={cx('uploaded')}>
        <div className={cx('table-operate')}>
          <h6>已选文件</h6>
          <Space>
            <Upload beforeUpload={beforeUpload} customRequest={() => {}} fileList={[]} multiple>
              <Button type="primary">选取本地文件</Button>
            </Upload>
            <Button
              disabled={uploadList.length <= 0}
              onClick={() => {
                uploadFileFunc(uploadList, 'batch');
              }}
            >
              挂接全部
            </Button>
            <Button onClick={clearUploadList}>清空列表</Button>
          </Space>
        </div>

        <Table
          size="small"
          dataSource={uploadList}
          rowKey="uid"
          loading={uploadTableLoading}
          scroll={{ y: 300 }}
          bordered
        >
          <Column title="文件名" dataIndex="name" key="name" align="center"></Column>
          <Column
            title="大小"
            dataIndex="size"
            key="size"
            align="center"
            render={(size: number) => byteConvert(size)}
          ></Column>
          <Column
            title={formatMessage('tableAction')}
            key="action"
            align="center"
            render={(_text, record: any) => (
              <Space>
                <Button
                  type="link"
                  onClick={() => {
                    uploadFileFunc([record]);
                  }}
                >
                  挂接
                </Button>
                <Button
                  type="link"
                  danger
                  onClick={() => {
                    delUploadItem(record.uid);
                  }}
                >
                  删除
                </Button>
              </Space>
            )}
          />
        </Table>
      </div>
      <div className={cx('linked')}>
        <div className={cx('table-operate')}>
          <h6>已挂接文件</h6>
          <Space>
            <Button type="primary" disabled>
              保存排序
            </Button>
            <Button disabled>删除所有</Button>
          </Space>
        </div>

        <Table size="small" dataSource={linkedList} bordered>
          <Column title="序号" dataIndex="sort_no" key="sort_no" align="center"></Column>
          <Column title="文件名" dataIndex="file_name" key="file_name" align="center"></Column>
          <Column
            title="大小"
            dataIndex="file_size"
            key="file_size"
            align="center"
            render={(size: number) => byteConvert(size)}
          ></Column>
          <Column title="扩展名" dataIndex="file_ext" key="file_ext" align="center"></Column>
          <Column
            title={formatMessage('tableAction')}
            key="action"
            align="center"
            render={(_text, record: any) => (
              <Space>
                <Button
                  type="link"
                  danger
                  onClick={() => {
                    delSelectFile(record.id);
                  }}
                >
                  删除
                </Button>
              </Space>
            )}
          />
        </Table>
      </div>
    </Modal>
  );
};

export default LinkDialog;
